<template>
  <el-dialog title="选择地图位置" v-model="show" custom-class="areaMap" width="1000px" :append-to-body="true"
             :close-on-press-escape="true" :close-on-click-modal="true" :destroy-on-close="true">
    <div class="mapContainer">
      <div class="mapContainer_tool">
        <div class="mapContainer_tool_search">
          <el-input type="text" id="searchInput" v-model="searchKey" placeholder="搜索关键词"></el-input>
        </div>
        <div class="mapContainer_detail" v-if="val">
          <div class="mapContainer_detail_h1">{{ val.address }}</div>
          <div class="mapContainer_detail_list">
            <div class="mapContainer_detail_list_li"><span>Lat:</span>{{ val.lat }}</div>
            <div class="mapContainer_detail_list_li"><span>Lng:</span>{{ val.lng }}</div>
            <div class="mapContainer_detail_list_li"><span>编码:</span>{{ val.adcode }}</div>
            <div class="mapContainer_detail_list_li"><span>地区:</span>{{ val.country }} - {{ val.province }} -
              {{ val.city }} - {{ val.district }}
            </div>
          </div>
          <div class="mapContainer_detail_btn">
            <el-button size="small" v-on:click="onCancel()">取消</el-button>
            <el-button size="small" type="primary" v-on:click="onConfirm">确定</el-button>
          </div>
        </div>
      </div>
      <div class="mapContainer_center" id="mapContainer"></div>
    </div>
  </el-dialog>
</template>

<script>
let AMap = window.AMap;

export default {
  data() {
    return {
      show: false,
      loading: false,
      searchKey: null,
      mapObject: null,
      marker: null,
      key: null,
      val: null
    }
  },
  props: {
    value: Object,
  },
  emits: ['success'],
  mounted() {
  },

  methods: {

    /**
     * 打开对话框
     */
    open(param = {}) {
      this.show = true
      this.mapObject = null
      this.searchKey = null
      this.marker = null
      this.key = param.key || null
      this.val = param.val || null

      this.initMap()
    },

    /**
     * 关闭对话框
     */
    close() {
      this.show = false;
    },

    /**
     * 加载地图
     **/
    initMap() {
      let self = this
      self.$nextTick(() => {
        self.mapObject = new AMap.Map('mapContainer', {
          zoom: 12,
          center: [121.810688, 39.06656],
          lang: 'zh_cn'
        });

        self.mapObject.addControl(new AMap.MapType({
          defaultType: 0
        }));

        self.mapObject.on('click', function (e) {
          if (self.marker) self.mapObject.remove(self.marker)
          self.drawMarker([e.lnglat.lng, e.lnglat.lat])
        });

        AMap.plugin('AMap.Autocomplete', function () {
          // 实例化Autocomplete
          var autoOptions = {
            city: '大连',
            input: 'searchInput'
          }
          var autoComplete = new AMap.Autocomplete(autoOptions);
          var placeSearch = new AMap.PlaceSearch({
            map: self.mapObject
          });
          AMap.event.addListener(autoComplete, "select", function (e) {
            placeSearch.setCity(e.poi.adcode);
            placeSearch.search(e.poi.name);  //关键字查询查询
          })
        })

        if (self.val) {
          self.drawMarker([self.val.lng, self.val.lat])
        }
      })
    },

    /**
     * 描画marker标记
     * @param lnglat
     */
    drawMarker(lnglat) {
      let self = this
      var icon = new AMap.Icon({
        size: new AMap.Size(15, 15),    // 图标尺寸
        image: 'https://www.amap.com/assets/img/stadiometry.png',  // Icon的图像
        imageSize: new AMap.Size(36, 15)   // 根据所设置的大小拉伸或压缩图片
      });
      var marker = new AMap.Marker({
        position: new AMap.LngLat(lnglat[0], lnglat[1]),
        offset: new AMap.Pixel(-10, -10),
        icon: icon,
        draggable: true
      });
      self.marker = marker
      self.mapObject.add(marker);
      self.getLocationInfoByMarker(lnglat)
    },

    /**
     * 检索位置信息
     * @param latLng
     */
    getLocationInfoByMarker(latLng) {
      let self = this
      AMap.service('AMap.Geocoder', function () {// 回调函数
        let geocoder = new AMap.Geocoder({});
        geocoder.getAddress(latLng, function (status, result) {
          if (status === 'complete' && result.info === 'OK') {
            self.val = {
              address: result.regeocode.formattedAddress,
              lng: latLng[0],
              lat: latLng[1],
              adcode: result.regeocode.addressComponent.adcode,
              city: result.regeocode.addressComponent.city,
              country: result.regeocode.addressComponent.country,
              district: result.regeocode.addressComponent.district,
              province: result.regeocode.addressComponent.province,
              street: result.regeocode.addressComponent.street,
              citycode: result.regeocode.addressComponent.citycode
            }
          }
        });
      });
    },

    /**
     * 取消选择
     */
    onCancel() {
      this.val = null
      if (this.marker) this.mapObject.remove(this.marker)
    },

    /**
     * 确定选择
     */
    onConfirm () {
      this.$emit("success", {
        key: this.key,
        val: this.val
      })
      this.onCancel()
      this.close()
    }
  },
  watch: {}
}
</script>
<style scoped lang="scss">
</style>
